package com.tangsm.spring.boot.deferred.result.executor;

import com.tangsm.spring.boot.deferred.result.domain.vo.Result;
import com.tangsm.spring.boot.deferred.result.domain.vo.Task;
import com.tangsm.spring.boot.deferred.result.queue.TaskQueue;
import com.tangsm.spring.boot.deferred.result.service.TaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Random;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 任务执行器
 *
 * @author tangsm
 */
@Component
public class TaskExecute {
    private static final Logger log = LoggerFactory.getLogger(TaskExecute.class);
    private static final Random random = new Random();

    @Autowired
    private TaskQueue taskQueue;

    @Autowired
    private TaskService taskService;

    /**
     * 初始化启动
     */
    @PostConstruct
    public void init() {
        log.info("开始持续处理任务");
        new Thread(this::execute).start();
    }

    /**
     * 持续处理
     * 返回执行结果
     */
    private void execute() {
        while (true) {
            ReentrantLock lock = new ReentrantLock();
            try {
                lock.lock();
                //取出任务
                Task task = taskQueue.take();
                if (task != null) {
                    // 业务处理（获取结果）
                    Result<String> result = taskService.getResult();
                    log.info("返回结果:{}", result);
                    task.getTaskResult().setResult(result);
                    return;
                }

                int time = random.nextInt(10);
                log.info("处理间隔：{}秒", time);
                Thread.sleep(time * 1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}
